import $ from "jquery";
import ProfileMgr from "../../libs/ProfileMgr.js";
class IndexPagination {
    constructor(showData, cb) {
        this.init.apply(this, arguments);
    }
    init(showData, cb) {
        this.cb = cb; // 渲染页面模块的回调函数
        this.showData = showData; //每页显示个数
        this.pageCount = 1; //当前页码
        this.totalData = 0; //加载数据的总长度
        this.data = []; //加载回来的数据
        this.dataLoaded = $.Callbacks();
        ProfileMgr.repeatLoad(); 
        this.listRender = new ListRender();
        this.listRender.init.call(this.listRender,".paging");
        this.loadData();
        this.bindEvent();
        

    }
    bindEvent() { 
        let that = this;
        this.dataLoaded.add($.proxy(this.getData, this));
        this.dataLoaded.add($.proxy(this.renderPage, this));
        this.dataLoaded.add($.proxy(this.saveStorage, this));
        
        $(".page").on("click", "li", function () {
            var a =that.data.slice(4 * $(this).index(), 4 * ($(this).index() + 1))
            that.listRender.setListData.call(that.listRender,a);
            that.cb();
        })
    }
    // 加载数据
    loadData() {
        $.ajax("./server/data.json", {
            dataType: "json"
        }).then(this.dataLoaded.fire);
    }
    // 得到所有数据
    getData(res) {
        this.data = res.data;
        this.totalData = this.data.length;
    }
    //加载完渲染第一页页面数据
    renderPage() {
        var b = this.data.slice(this.pageCount - 1, this.showData)
        this.listRender.setListData.call(this.listRender,b);
        this.cb();
    }
    // 保存所有数据
    saveStorage(res){
        ProfileMgr.setGoodsList(res.data);
    }
 
}


function ListRender(){

}
Object.assign(ListRender.prototype,{
    init: function(selector, callback){
        this.m_ulEle = document.querySelector(selector);
    }
    ,
    // 渲染列表数据
    render: function(data){
        let html = ``;
        data.forEach((item)=>{
            html += this.createOneItem(item);
        });
        this.m_ulEle.innerHTML = html;
    }
    ,
    // 设置要渲染的总数据
    setListData: function(data){
        this.render(data);
    }
    ,
    // 创建单个item
    createOneItem: function(info){
        return `<div class="paging_list">
        <a href="${info.link_url}">
            <img src="" data-src ="${info.img}">
            <p>${info.name}</p>
            <div>
                <span style=" color: red;font-weight: bold;">${info.price}</span>
                <span style=" margin-left: 12px;text-decoration: line-through;color: #c7c7c7;">￥${info.oprice}</span>
            </div>
        </a>
    </div>`;
    }

})

module.exports = IndexPagination;